<template>
  <div class="login">
    <div class="bg">
      <el-dialog
        v-model="loginModal"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :modal="false"
        :show-close="false"
        class="login-dialog"
        width="300px">
        <template #header>
          <div style="text-align: center">
            <h1>
              <span>{{ title }}</span>
            </h1>
            <div style="height: 20px">
              <span style="text-align: center; font-size: x-small">v{{ version }}</span>
            </div>
          </div>
        </template>
        <div>
          <el-form ref="loginForm" :model="formValidate" :rules="ruleValidate" @submit.prevent>
            <el-form-item>
              <input style="display: none" type="password" />
            </el-form-item>
            <el-form-item prop="loginNo">
              <el-input
                ref="loginNo"
                v-model="formValidate.loginNo"
                :disabled="modal_loading"
                :placeholder="text.usernamePlaceholder"
                prefix-icon="el-icon-user"
                type="text"
                @keyup.enter="handleSubmit">
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="formValidate.password"
                :disabled="modal_loading"
                :placeholder="text.passwordPlaceholder"
                autocomplete="off"
                prefix-icon="el-icon-lock"
                type="text"
                @focus="passwordFocus"
                @keyup.enter="handleSubmit">
              </el-input>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-checkbox
                v-model="formValidate.remember"
                :disabled="modal_loading"
                @keyup.enter="handleSubmit">
                {{ text.rememberMe }}
              </el-checkbox>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div style="text-align: center">
            <el-button
              :loading="modal_loading"
              style="width: 100%"
              type="primary"
              @click="handleSubmit">
              {{ text.loginButton }}
            </el-button>
            <small style="text-align: center; display: block; margin-top: 10px">{{
              copyright
            }}</small>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import '@/assets/styles/login.less'
import { nextTick, ref } from 'vue'
import { getRedirect } from '@/libs/tools'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'

export default {
  name: 'login',
  data() {
    return {
      title: this.appStore.appInfo.appName,
      version: this.appStore.appInfo.appVersion,
      copyright: this.appStore.appInfo.copyright,
      homePath: this.appStore.appInfo.homePath,
      text: {
        usernamePlaceholder: this.t('forms.pleaseEnter') + this.t('forms.loginNo'),
        passwordPlaceholder: this.t('forms.pleaseEnter') + this.t('forms.password'),
        rememberMe: this.t('forms.rememberMe'),
        loginButton: this.t('forms.buttons.login')
      },
      loginModal: true,
      modal_loading: false,
      formValidate: {
        loginNo: this.appStore.user.loginNo,
        password: '',
        remember: this.appStore.user.remember
      },
      ruleValidate: {
        loginNo: [
          {
            required: true,
            message: this.t('forms.loginNo') + this.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.t('forms.password') + this.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    passwordFocus(event) {
      event.target.type = 'password'
    },
    handleSubmit() {
      const currObj = this
      currObj.loginForm.validate((valid) => {
        if (valid) {
          currObj.modal_loading = true
          currObj.$api.request.auth
            .doLogin(currObj.formValidate.loginNo, currObj.formValidate.password)
            .then((res) => {
              if (res) {
                if (res.data.access_token) {
                  currObj.$message.success(currObj.t('messages.loginSuccess') + '')
                  currObj.appStore.setToken(res.data.access_token)
                  if (res.data.token_type === 'bearer' || res.data.token_type === 'Bearer') {
                    currObj.appStore.setTokenType('Bearer')
                  } else {
                    currObj.appStore.setTokenType(res.data.token_type)
                  }
                  currObj.appStore.setWarmToken(
                    `${currObj.appStore.user.tokenType} ${currObj.appStore.user.token}`
                  )
                  currObj.appStore.setScope(res.data.scope)
                  if (currObj.formValidate.remember) {
                    currObj.appStore.setLoginNo(currObj.formValidate.loginNo)
                  } else {
                    currObj.appStore.setLoginNo('')
                  }
                  currObj.appStore.setRemember(currObj.formValidate.remember)
                  let redirect = getRedirect(this.appStore, currObj.$route)
                  if (!redirect || redirect === '/login') {
                    redirect = currObj.homePath
                  }
                  currObj.$router.replace(redirect)
                } else {
                  currObj.$api.errorProcess(
                    currObj.t('messages.loginInvalid'),
                    currObj.t('messages.loginFailed')
                  )
                }
              }
              currObj.modal_loading = false
            })
            .catch((error) => {
              currObj.modal_loading = false
              currObj.$api.errorProcess(error, currObj.t('messages.loginFailed'))
            })
        }
      })
    }
  },
  mounted() {
    this.appStore.loginOut()
    nextTick(() => {
      this.loginNo.focus()
    })
  },
  setup() {
    const loginForm = ref(null)
    const loginNo = ref(null)
    const { t } = useI18n()
    const appStore = useAppStore()
    return { loginForm, loginNo, t, appStore }
  }
}
</script>
